#!/usr/bin/python

# This file is part of Gehyra.
#
# Gehyra is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gehyra is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gehyra.  If not, see <http://www.gnu.org/licenses/>.

"""@file gehyra.py
Gehyra entry point.
$Id$
"""

import sys
import gehyra.build_info as build_info
from gehyra.common.logger import LOG as LOG
from gehyra.common.interfaces import verify_interfaces
from gehyra.config.manager import Manager as ConfigManager
from gehyra.core.gehyra_node import GehyraNode

def main(argv = sys.argv):
    """Gehyra entry point.
    Parses command line parameters and acts accordingly
    @param argv Optional list of commandline arguments
    """

    from optparse import OptionParser, OptionGroup, IndentedHelpFormatter
    parser = OptionParser(
        usage = "Usage: %prog [OPTIONS] [config.cfg]",
        description = "Run Gehyra with the given configuration file. If no path"
                      "is given, Gehyra will use the default file",
        version = "%s" % (build_info.VERSION),
        formatter = IndentedHelpFormatter(max_help_position=25)
    )

    class MyOptGroup(OptionGroup):
        """custom optgroup class that doesn't indent option group sections"""
        def format_help(self, formatter):
            """format_help"""
            formatter.dedent()
            s = OptionGroup.format_help(self, formatter)
            formatter.indent()
            return s

    try:
        import gehyra.core
    except ImportError:
        pass
    else:
        parser.add_option("-c", "--config-path", type="string", metavar="PATH",
                          dest="config_path", default="",
                          help="explicitly specify the configuration path")
        parser.add_option("-m", "--make-config", action="store_true", 
                          dest="make_config", default=False,
                          help="write the default configuration data into the "
                          "configuration file specified")
        parser.add_option("-t", "--terminate", action="store_true",
                          dest="terminate", default=False,
                          help="terminate an already-running Gehyra node")

    ## @todo: think of a better way of doing this test -
    ## basically "if running from source" rather than py2exe or py2app compiled
    if argv[0] == "gehyra.py":

        group = MyOptGroup(parser, "Debug options",
            "These options are only useful to developers")
        group.add_option("-v", "--verbose", action="store_true",
                         dest="verbose", default=False,
                         help="provide verbose logging information")
        group.add_option("-p", "--port", type="int", metavar="PORT", 
                         dest="port", default=-1, help="listen for the DC "
                         "client on localhost:PORT. If none is given, the last "
                         "one to be used will be used")
        group.add_option("-e", "--emulate", type="string", metavar="NAME",
                         dest="emulate", default="",
                         help="run the specified emulation module")
        group.add_option("-r", "--run-tests", action="append", type="string", 
                         metavar="LIST", dest="tests", default=[],
                         help="run the specified test suites")
        parser.add_option_group(group)

    try:
        import gehyra.bridge
    except ImportError:
        pass
    else:
        group = MyOptGroup(parser, "Bridge mode options",
            "This should only be used by network administrators")
        group.add_option("-b", "--bridge", action="store_true", dest="bridge", 
                         default=False, help="run this node as a bridge")
        group.add_option("-u", "--update", type="string", metavar="LIST",
                         dest="update", default="", help="run this node as a "
                         "bridge subset which periodically updates the "
                         "specified list of bootstrap options.  If no list is "
                         "provided, all boostrap sources described in the "
                         "configuration file will be updated")
        parser.add_option_group(group)


    (opts, args) = parser.parse_args()

    # LOG.debug("Command Line Options: %s" % opts)
    # LOG.debug("Command Line Arguments: %s" % args)

    if len(opts.tests):
        from gehyra.test.runner import run_tests
        run_tests(opts.tests)

    else:

        # if the verification fails, bail (this will save developer headaches)
        if verify_interfaces() is not True:
            LOG.critical("Some interface verification tests failed")
            return 147

        # if we fail to load enough configuration, bail
        cfg_mgr = ConfigManager(None)
        if cfg_mgr.load_config(opts.config_path, opts.bridge) is not True:
            LOG.critical("Unable to load the minimum configuration to run")
            return 148

        node = GehyraNode(cfg_mgr)

        if node.initialize() is not True:
            LOG.critical("Unable to initalize sufficient components to run")
            return 149

        ## @todo remove when stable
        LOG.setPacketLogging("ADC", True) 

        node.start()

    return 0


if __name__ == "__main__":
    sys.exit(main())
